package hn.cch.async.service;

import hn.cch.async.task.CustomizeTask;
import hn.cch.async.task.TaskConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.ScheduledFuture;

@Service
public class ScheduledServiceImpl implements ScheduledService {

    private static final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);


    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;


    public void start(CustomizeTask customizeTask) {
        if (TaskConfiguration.cache.containsKey(customizeTask.getTaskName())) {
            logger.error("任务名称【{}】重复", customizeTask.getTaskName());
            return;
        }
        ScheduledFuture<?> scheduledFuture = threadPoolTaskScheduler.schedule(customizeTask,
            new CronTrigger(customizeTask.getTaskCorn()));
        assert scheduledFuture != null;
        TaskConfiguration.cache.put(customizeTask.getTaskName(), scheduledFuture);
        logger.info("【{}】触发【{}】任务调度成功", customizeTask.getTaskCorn(), customizeTask.getTaskName());
    }


    public void stop(String taskName) {
        ScheduledFuture<?> scheduledFuture = TaskConfiguration.cache.get(taskName);
        if (Objects.nonNull(scheduledFuture)) {
            // 取消调度，可能中断正在运行的线程
            if (scheduledFuture.cancel(true)) {
                TaskConfiguration.cache.remove(taskName);
                logger.info("【{}】任务暂停成功", taskName);
            } else {
                logger.error("【{}】任务无法取消调度", taskName);
            }
        } else {
            logger.error("【{}】任务不存在", taskName);
        }


    }
}